#include "adminmenuwidget.h"
#include <QMenu>
#include <QDialog>
#include <QListWidget>
#include <QListWidgetItem>

// 这个文件包含AdminMenuWidget的槽函数实现



void AdminMenuWidget::showStatusMessage(const QString &message, bool isError)
{
    m_statusLabel->setText(message);
    
    // 直接设置QPushButton的样式（按钮背景更可靠）
    if (isError) {
        // 错误状态：红色背景
        m_statusLabel->setStyleSheet(
            "QPushButton { "
            "background-color: #fdf2f2; "
            "color: #e74c3c; "
            "border: 2px solid #f5c6cb; "
            "border-radius: 4px; "
            "padding: 6px 12px; "
            "font-size: 12px; "
            "font-weight: bold; "
            "text-align: center; "
            "}"
            "QPushButton:disabled { "
            "background-color: #fdf2f2; "
            "color: #e74c3c; "
            "border: 2px solid #f5c6cb; "
            "}"
        );
    } else {
        // 成功状态：绿色背景
        m_statusLabel->setStyleSheet(
            "QPushButton { "
            "background-color: #f0f9f0; "
            "color: #27ae60; "
            "border: 2px solid #c3e6cb; "
            "border-radius: 4px; "
            "padding: 6px 12px; "
            "font-size: 12px; "
            "font-weight: bold; "
            "text-align: center; "
            "}"
            "QPushButton:disabled { "
            "background-color: #f0f9f0; "
            "color: #27ae60; "
            "border: 2px solid #c3e6cb; "
            "}"
        );
    }
    
    // 强制重绘
    m_statusLabel->update();
    m_statusLabel->repaint();
    
    emit statusMessageChanged(message, isError ? 0 : 3000);
}

void AdminMenuWidget::enableOperationButtons(bool enabled)
{
    m_editButton->setEnabled(enabled);
    m_deleteButton->setEnabled(enabled);
}

int AdminMenuWidget::getSelectedRowIndex()
{
    QList<QTableWidgetItem*> selectedItems = m_menuTable->selectedItems();
    if (selectedItems.isEmpty()) {
        return -1;
    }
    return selectedItems.first()->row();
}

QString AdminMenuWidget::getSelectedMenuItemId()
{
    int row = getSelectedRowIndex();
    if (row < 0 || row >= m_menuTable->rowCount()) {
        return QString();
    }
    
    QTableWidgetItem *idItem = m_menuTable->item(row, COL_ID);
    return idItem ? idItem->text() : QString();
}



// 槽函数实现
void AdminMenuWidget::onMenuItemSelectionChanged()
{
    QString itemId = getSelectedMenuItemId();
    bool hasSelection = !itemId.isEmpty();
    
    enableOperationButtons(hasSelection);
}

void AdminMenuWidget::onAddMenuItemClicked()
{
    if (!m_menuManager) {
        showStatusMessage("菜单管理器未初始化", true);
        return;
    }
    
    MenuItemEditDialog dialog(this);
    dialog.setMenuManager(m_menuManager);
    dialog.setAddMode(m_categories);
    
    // 连接信号
    connect(&dialog, &MenuItemEditDialog::menuItemSaved, this, [this](const MenuItem &item, bool isNewItem) {
        Q_UNUSED(item)
        Q_UNUSED(isNewItem)
        // 刷新数据显示
        loadMenuData();
        updateCategoryFilter();
        filterMenuData();
        showStatusMessage("菜品添加成功");
    });
    
    dialog.exec();
}

void AdminMenuWidget::onEditMenuItemClicked()
{
    QString itemId = getSelectedMenuItemId();
    if (itemId.isEmpty()) {
        showStatusMessage("请先选择要编辑的菜品", true);
        return;
    }
    
    if (!m_menuManager) {
        showStatusMessage("菜单管理器未初始化", true);
        return;
    }
    
    MenuItem item = m_menuManager->getMenuItemById(itemId);
    if (!item.isValid()) {
        showStatusMessage("菜品不存在", true);
        return;
    }
    
    MenuItemEditDialog dialog(this);
    dialog.setMenuManager(m_menuManager);
    dialog.setEditMode(item, m_categories);
    
    // 连接信号
    connect(&dialog, &MenuItemEditDialog::menuItemSaved, this, [this](const MenuItem &item, bool isNewItem) {
        Q_UNUSED(item)
        Q_UNUSED(isNewItem)
        // 刷新数据显示
        loadMenuData();
        updateCategoryFilter();
        filterMenuData();
        showStatusMessage("菜品更新成功");
    });
    
    dialog.exec();
}

void AdminMenuWidget::onDeleteMenuItemClicked()
{
    QString itemId = getSelectedMenuItemId();
    if (itemId.isEmpty()) {
        showStatusMessage("请先选择要删除的菜品", true);
        return;
    }
    
    MenuItem item = m_menuManager->getMenuItemById(itemId);
    if (!item.isValid()) {
        showStatusMessage("菜品不存在", true);
        return;
    }
    
    QMessageBox msgBox(this);
    msgBox.setIcon(QMessageBox::Question);
    msgBox.setWindowTitle("确认删除");
    msgBox.setText(QString("确定要删除菜品 \"%1\" 吗？\n此操作无法撤销。").arg(item.name));
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    msgBox.setStyleSheet(getMessageBoxStyleSheet());
    int ret = msgBox.exec();
    
    if (ret == QMessageBox::Yes) {
        MenuOperationResult result = m_menuManager->deleteMenuItem(itemId);
        if (result == MenuOperationResult::SUCCESS) {
            showStatusMessage("菜品删除成功");
        } else {
            showStatusMessage(MenuManager::getOperationResultMessage(result), true);
        }
    }
}



void AdminMenuWidget::onSearchTextChanged()
{
    // 通过定时器实现防抖
    m_searchTimer->stop();
    m_searchTimer->start();
}

void AdminMenuWidget::onCategoryFilterChanged()
{
    filterMenuData();
}

void AdminMenuWidget::onRefreshClicked()
{
    refreshData();
}

void AdminMenuWidget::onManageCategoriesClicked()
{
    showCategoryManagementDialog();
}

void AdminMenuWidget::onTableItemDoubleClicked(int row, int column)
{
    Q_UNUSED(column)
    if (row >= 0 && row < m_menuTable->rowCount()) {
        // 获取选中菜品的ID
        QTableWidgetItem *idItem = m_menuTable->item(row, COL_ID);
        if (idItem && m_menuManager) {
            QString itemId = idItem->text();
            MenuItem item = m_menuManager->getMenuItemById(itemId);
            if (item.isValid()) {
                // 显示菜品详情对话框
                showMenuItemDetailsDialog(item);
            }
        }
    }
}

void AdminMenuWidget::onTableContextMenuRequested(const QPoint &pos)
{
    QTableWidgetItem *item = m_menuTable->itemAt(pos);
    if (!item) return;
    
    QMenu contextMenu(this);
    contextMenu.addAction("编辑", this, &AdminMenuWidget::onEditMenuItemClicked);
    contextMenu.addAction("删除", this, &AdminMenuWidget::onDeleteMenuItemClicked);
    contextMenu.addSeparator();
    contextMenu.addAction("刷新", this, &AdminMenuWidget::onRefreshClicked);
    
    contextMenu.exec(m_menuTable->mapToGlobal(pos));
}

// MenuManager信号响应
void AdminMenuWidget::onMenuItemAdded(const MenuItem &item)
{
    m_allMenuItems.append(item);
    filterMenuData();
    showStatusMessage(QString("菜品 \"%1\" 已添加").arg(item.name));
}

void AdminMenuWidget::onMenuItemUpdated(const MenuItem &item)
{
    // 更新缓存中的数据
    for (int i = 0; i < m_allMenuItems.size(); ++i) {
        if (m_allMenuItems[i].id == item.id) {
            m_allMenuItems[i] = item;
            break;
        }
    }
    
    // 直接更新表格中对应行的数据，避免完全重新加载表格
    for (int row = 0; row < m_menuTable->rowCount(); ++row) {
        QTableWidgetItem *idItem = m_menuTable->item(row, COL_ID);
        if (idItem && idItem->text() == item.id) {
            // 更新菜品名称
            QTableWidgetItem *nameItem = m_menuTable->item(row, COL_NAME);
            if (nameItem) {
                nameItem->setText(item.name);
            }
            
            // 更新分类
            QTableWidgetItem *categoryItem = m_menuTable->item(row, COL_CATEGORY);
            if (categoryItem) {
                categoryItem->setText(item.category);
            }
            
            // 更新价格
            QTableWidgetItem *priceItem = m_menuTable->item(row, COL_PRICE);
            if (priceItem) {
                priceItem->setData(Qt::DisplayRole, item.price);
            }
            
            // 更新库存（与onStockUpdated保持一致）
            QTableWidgetItem *stockItem = m_menuTable->item(row, COL_STOCK);
            if (stockItem) {
                stockItem->setData(Qt::DisplayRole, item.stock);
                
                // 更新颜色
                if (item.stock <= 5) {
                    stockItem->setBackground(QColor("#ffebee"));
                    stockItem->setForeground(QColor("#d32f2f"));
                } else {
                    stockItem->setBackground(QColor());
                    stockItem->setForeground(QColor());
                }
            }
            
            // 更新销量
            QTableWidgetItem *salesItem = m_menuTable->item(row, COL_SALES);
            if (salesItem) {
                salesItem->setData(Qt::DisplayRole, item.salesCount);
            }
            
            break;
        }
    }
    
    // 更新过滤后的数据列表
    for (int i = 0; i < m_filteredMenuItems.size(); ++i) {
        if (m_filteredMenuItems[i].id == item.id) {
            m_filteredMenuItems[i] = item;
            break;
        }
    }
    
    showStatusMessage(QString("菜品 \"%1\" 已更新").arg(item.name));
}

void AdminMenuWidget::onMenuItemDeleted(const QString &itemId)
{
    // 从缓存中移除
    for (int i = 0; i < m_allMenuItems.size(); ++i) {
        if (m_allMenuItems[i].id == itemId) {
            QString itemName = m_allMenuItems[i].name;
            m_allMenuItems.removeAt(i);
            filterMenuData();
            showStatusMessage(QString("菜品 \"%1\" 已删除").arg(itemName));
            break;
        }
    }
}

void AdminMenuWidget::onStockUpdated(const QString &itemId, int oldStock, int newStock)
{
    Q_UNUSED(oldStock)
    
    // 更新表格中的库存显示
    for (int row = 0; row < m_menuTable->rowCount(); ++row) {
        QTableWidgetItem *idItem = m_menuTable->item(row, COL_ID);
        if (idItem && idItem->text() == itemId) {
            QTableWidgetItem *stockItem = m_menuTable->item(row, COL_STOCK);
            if (stockItem) {
                stockItem->setData(Qt::DisplayRole, newStock);
                
                // 更新颜色
                if (newStock <= 5) {
                    stockItem->setBackground(QColor("#ffebee"));
                    stockItem->setForeground(QColor("#d32f2f"));
                } else {
                    stockItem->setBackground(QColor());
                    stockItem->setForeground(QColor());
                }
            }
            break;
        }
    }
    
    // 注意：库存更新时不需要处理表单，因为已移除编辑表单
}

void AdminMenuWidget::onCategoriesChanged(const QStringList &categories)
{
    m_categories = categories;
    updateCategoryFilter();
}

void AdminMenuWidget::onSalesCountUpdated(const QString &itemId, int newSalesCount)
{
    // 更新表格中的销量显示
    for (int row = 0; row < m_menuTable->rowCount(); ++row) {
        QTableWidgetItem *idItem = m_menuTable->item(row, COL_ID);
        if (idItem && idItem->text() == itemId) {
            QTableWidgetItem *salesItem = m_menuTable->item(row, COL_SALES);
            if (salesItem) {
                salesItem->setData(Qt::DisplayRole, newSalesCount);
                
                // 可选：为销量高的菜品添加特殊样式
                if (newSalesCount >= 100) {
                    salesItem->setBackground(QColor("#e8f5e8"));
                    salesItem->setForeground(QColor("#2e7d32"));
                } else if (newSalesCount >= 50) {
                    salesItem->setBackground(QColor("#fff3e0"));
                    salesItem->setForeground(QColor("#ef6c00"));
                } else {
                    salesItem->setBackground(QColor());
                    salesItem->setForeground(QColor());
                }
            }
            break;
        }
    }
    
    // 更新内存中的数据
    for (int i = 0; i < m_allMenuItems.size(); ++i) {
        if (m_allMenuItems[i].id == itemId) {
            m_allMenuItems[i].salesCount = newSalesCount;
            break;
        }
    }
}

void AdminMenuWidget::showCategoryManagementDialog()
{
    // 简单的分类管理对话框
    QDialog dialog(this);
    dialog.setWindowTitle("分类管理");
    dialog.setModal(true);
    dialog.resize(300, 200);
    
    QVBoxLayout *layout = new QVBoxLayout(&dialog);
    
    QLabel *label = new QLabel("当前分类列表:", &dialog);
    layout->addWidget(label);
    
    QListWidget *categoryList = new QListWidget(&dialog);
    categoryList->addItems(m_categories);
    layout->addWidget(categoryList);
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *addBtn = new QPushButton("添加", &dialog);
    QPushButton *deleteBtn = new QPushButton("删除", &dialog);
    QPushButton *closeBtn = new QPushButton("关闭", &dialog);
    
    buttonLayout->addWidget(addBtn);
    buttonLayout->addWidget(deleteBtn);
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeBtn);
    layout->addLayout(buttonLayout);
    
    // 连接信号
    connect(addBtn, &QPushButton::clicked, [&]() {
        bool ok;
        QString category = QInputDialog::getText(&dialog, "添加分类", "分类名称:", QLineEdit::Normal, "", &ok);
        if (ok && !category.trimmed().isEmpty()) {
            if (m_menuManager->addCategory(category.trimmed())) {
                categoryList->addItem(category.trimmed());
                showStatusMessage(QString("分类 \"%1\" 添加成功").arg(category.trimmed()));
            }
        }
    });
    
    connect(deleteBtn, &QPushButton::clicked, [&]() {
        QListWidgetItem *item = categoryList->currentItem();
        if (item) {
            QString category = item->text();
            QMessageBox msgBox(&dialog);
            msgBox.setIcon(QMessageBox::Question);
            msgBox.setWindowTitle("确认删除");
            msgBox.setText(QString("确定要删除分类 \"%1\" 吗？").arg(category));
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            msgBox.setDefaultButton(QMessageBox::No);
            msgBox.setStyleSheet(getMessageBoxStyleSheet());
            int ret = msgBox.exec();
            if (ret == QMessageBox::Yes) {
                if (m_menuManager->removeCategory(category)) {
                    delete categoryList->takeItem(categoryList->row(item));
                    showStatusMessage(QString("分类 \"%1\" 删除成功").arg(category));
                }
            }
        }
    });
    
    connect(closeBtn, &QPushButton::clicked, &dialog, &QDialog::accept);
    
    dialog.exec();
}

void AdminMenuWidget::onExternalFileChanged(DataType dataType, const QString& /*filePath*/)
{
    // 当检测到外部文件变更时，刷新相关数据
    if (dataType == DataType::MENU) {
        // 延迟刷新，确保文件写入完成
        QTimer::singleShot(100, this, [this]() {
            refreshData();
            showStatusMessage("检测到菜单数据更新，已自动刷新", false);
        });
    }
}



